package utils;

import java.util.LinkedList;

public class ResourceCritical<R>
{
    private LinkedList<R> buffer;
    private int           maxBufferSize;

    public ResourceCritical(int bufferSize)
    {
        buffer = new LinkedList<R>();
        maxBufferSize = bufferSize;
    }

    public synchronized void push(R resource)
    {
        try
        {
            if (buffer.size() >= maxBufferSize)
            {
                buffer.remove();
            }
            buffer.add(resource);
            notify();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    public synchronized R pop()
    {
        while (buffer.size() == 0)
        {
            try
            {
                wait();
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
        return buffer.remove();
    }
}
